package com.smarttest.common.util.protocol.StringResolve;

import java.io.BufferedReader;
import java.io.IOException;

import com.smarttest.common.beans.protolcol.SmartMessage;
import com.smarttest.common.exceptions.NoCheckSumException;
import com.smarttest.common.exceptions.WrongLengthException;
import com.smarttest.common.util.protocol.SmartUtils;
//处理报文字符工具类
//Author:xiezhenyu
public class MessageStringResolveUtils {
	//根据文件输入格式去除不必要字符并返回SmartMessage
	public static SmartMessage formatMessage(String rawMessage,String mark,boolean ismandatory) throws NoCheckSumException, WrongLengthException {
		int msgStartAlarmIndex = rawMessage.indexOf(mark);
		if (msgStartAlarmIndex > -1) {
			String rawMessage2 = rawMessage.substring(msgStartAlarmIndex);
			String message = rawMessage2.substring(3,rawMessage2.length()-3);
			byte[] bytes = SmartUtils.str2bytes(message);
			SmartMessage sm = new SmartMessage(bytes,ismandatory);
			if(sm.getData()==null){
				return null;
			}
			return sm;
		}
		else {
			return null;
		}
	}
	
	//用于报文过长分为几段的情况，遍历获取消息结尾并返回整条报文
	public static StringBuffer getWholeMessage(BufferedReader br,String cmdStart) throws IOException{
		String dataline = null;
		StringBuffer sb = new StringBuffer();
		while ((dataline = br.readLine()) != null) {
			if(!dataline.contains(cmdStart)){
				sb.append(" " + formartMessage2(dataline));
			}
			else{
				sb.append(" " + formartMessage2(dataline));
				break;
			}
		}
		return sb;
	}
	
	//用于报文过长分为几段的情况，获取非7E开始消息头，以<=和=>标记报文起始位置
	public static String formartMessage2(String rawMessage){
		int upstream = rawMessage.indexOf("<=");
		int downstram = rawMessage.indexOf("=>");
	    if(upstream>0){
	    	return rawMessage.substring(upstream+3);
	    }else if(downstram > 0){
	    	return rawMessage.substring(downstram+3);
	    }else{
	    	 return null;
	    }
	}
}
